package cn.icanci.loopstack.plugin.dalgen.mojo;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.icanci.loopstack.plugin.dalgen.process.GeneratorProcessor;
import cn.icanci.loopstack.plugin.dalgen.process.MojoGoalGeneratorProcessor;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.components.interactivity.Prompter;
import org.codehaus.plexus.components.interactivity.PrompterException;

import com.google.common.base.Preconditions;

/**
 * 插件执行处理器抽象
 * 
 * @author icanci
 * @since 1.0 Created in 2022/05/14 10:11
 */
public abstract class AbstractDalGenMojo extends AbstractMojo {
    /**
     * 配置文件路径
     */
    @Parameter(property = "configFiles", required = true)
    protected List<String> configFiles;
    /**
     * 项目
     */
    @Parameter(defaultValue = "${project}", readonly = true, required = true)
    protected MavenProject mavenProject;
    /**
     * Component used to prompt for input
     */
    @Component
    protected Prompter     prompter;

    /**
     * list to map
     *
     * @return {@link Map}<{@link Integer}, {@link String}>
     */
    protected Map<Integer, String> list2Map() {
        Preconditions.checkArgument(CollUtil.isNotEmpty(configFiles), "未指定 dal-gen.properties 配置文件");
        Map<Integer, String> xmlMap = new HashMap<>();
        for (int i = 0; i < configFiles.size(); i++) {
            xmlMap.put(i + 1, configFiles.get(i));
        }
        return xmlMap;
    }

    /**
     * 提示选择 DB
     *
     * @return {@link String}
     * @throws PrompterException 提词员异常
     */
    private String prompterDb() throws PrompterException {
        Map<Integer, String> map = list2Map();

        if (map.size() == 1) {
            return map.values().stream().findFirst().get();
        }

        System.out.println("---------------------[ Generator Config File List ]---------------------\"");
        for (Map.Entry<Integer, String> m : map.entrySet()) {
            System.out.println(StrUtil.format("⏭ [{}] {}", m.getKey(), m.getValue()));
        }
        System.out.println("------------------------------------------------------------------------");
        String prompt = prompter.prompt("⚠️请选择一个目标配置文件（数字序号）");
        System.out.println("------------------------------------------------------------------------");
        Preconditions.checkArgument(NumberUtil.isNumber(prompt), "输入有误，请输入指定序号");
        String xmlFileName = map.get(Integer.parseInt(prompt));
        Preconditions.checkArgument(StrUtil.isNotBlank(xmlFileName), StrUtil.format("输入有误，{} 不存在", xmlFileName));
        String configFilePath = getConfigFilePath(xmlFileName);
        System.out.println(StrUtil.format("✅configFilePath:{}", configFilePath));
        return configFilePath;
    }

    /**
     * 执行生成
     *
     * @param processor processor
     */
    protected void generator(MojoGoalGeneratorProcessor processor) throws PrompterException {
        String configFilePath = prompterDb();
        MavenProject parent = mavenProject;
        while (parent.getParent() != null) {
            parent = parent.getParent();
        }
        String projectParentPath = parent.getBasedir().toString();
        System.setProperty("maven.user.dir", projectParentPath);
        GeneratorProcessor generatorProcessor = new GeneratorProcessor(processor, configFilePath);
        processor.consumer.accept(generatorProcessor);
    }

    /**
     * 获取配置文件
     *
     * @param fileName 文件名称
     * @return {@link String}
     */
    protected String getConfigFilePath(String fileName) {
        return new File(StrUtil.join(File.separator, mavenProject.getBasedir().getPath(), fileName)).getPath();
    }
}
